package com.linkoog.devtools.maven.repository_clean.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.maven.project.MavenGeneralSettings;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.project.StaticResolvedMavenHomeType;
import org.jetbrains.idea.maven.utils.MavenWslUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MavenRepositoryCleanAction extends AnAction {


    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        final Project project = e.getProject();
        if (project == null) return;

        final MavenGeneralSettings generalSettings = MavenProjectsManager.getInstance(project).getGeneralSettings();
        File localRepositoryFile = MavenWslUtil.getLocalRepo(project, generalSettings.getLocalRepository(), (StaticResolvedMavenHomeType) generalSettings.getMavenHomeType(), generalSettings.getUserSettingsFile(), generalSettings.getMavenConfig());
        if (!localRepositoryFile.exists()) return;


        String localRepository = localRepositoryFile.getAbsolutePath();
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "清除maven本地仓库", true) {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                try {
                    Path folder = Paths.get(localRepository);
                    Files.walk(folder)
                            .filter(Files::isRegularFile)
                            .filter(path -> path.getFileName().toString().endsWith(".lastUpdated"))
                            .forEach(path -> {
                                try {
                                    Files.delete(path);
                                    indicator.setText( path.toAbsolutePath() + "删除成功");
                                } catch (IOException ex) {
                                    indicator.setText( path.toAbsolutePath() + "删除失败");
                                }
                            });
                    indicator.setText("已清除maven本地仓库");
                } catch (IOException exception) {
                    indicator.setText("清除maven本地仓库失败： " + exception.getMessage());
                }
                indicator.setIndeterminate(true);
            }
        });
    }

}
